package com.project.application.server.system.controller;

import com.project.application.common.constant.Constants;
import com.project.application.common.exception.ServiceException;
import com.project.application.common.utils.StringUtils;
import com.project.application.common.utils.file.FileUploadUtils;
import com.project.application.common.utils.file.FileUtils;
import com.project.application.framework.config.AppConfig;
import com.project.application.framework.config.ServerConfig;
import com.project.application.framework.security.service.TokenService;
import com.project.application.framework.web.controller.BaseController;
import com.project.application.framework.web.domain.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;


/**
 * @author :levnli
 */
@RestController
@RequestMapping("/common")
@Api(tags = {"通用工具"})
public class CommonController extends BaseController {

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private TokenService tokenService;

    /**
     * 获取当前登录用户信息
     * @param request 请求
     * @return 用户信息
     */
    @ApiOperation("获取当前登录用户信息")
    @GetMapping("/getUserInfo")
    public AjaxResult getUserInfo(HttpServletRequest request) {
        return toAjax(tokenService.getLoginUser(request).getUser());
    }

    /**
     * 通用上传请求
     */
    @ApiOperation("上传")
    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file) {
        try {
            // 上传文件路径
            String filePath = AppConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            return toAjax(Objects.requireNonNull(build().put("fileName", fileName)).put("url", url));
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 下载
     *
     * @param fileUrl 文件路径
     */
    @ApiOperation("下载")
    @GetMapping("/download")
    public void downloadFile(String fileUrl, HttpServletResponse response) {
        if (StringUtils.isBlank(fileUrl)) {
            throw new ServiceException("文件地址为空");
        }
        try {
            if (!FileUtils.checkAllowDownload(fileUrl)) {
                throw new ServiceException(StringUtils.format("资源文件({})非法，不允许下载。 ", fileUrl));
            }
            // 本地资源路径
            String localPath = AppConfig.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(fileUrl, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }
}
